package com.baixiaowen.xiaoaointerview.并发基础篇;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 自定义锁 实现 AQS 框架
 *
 *      AQS框架其实可以理解为是一种控制反转的架构，即锁控制程序由用户来编写，AQS为其生成原子操作
 *
 * @author Baixiaowen
 */
public class CustomLock {

    static class Mutex extends AbstractQueuedSynchronizer {

        @Override
        protected boolean tryAcquire(int arg) {
            return compareAndSetState(0, 2);
        }

        @Override
        protected boolean tryRelease(int arg) {
            return compareAndSetState(2, 0);
        }

    }

    public static int i = 0;

    public static void main(String[] args) throws InterruptedException {
        Mutex mutex = new Mutex();

        Thread t1 = new Thread(() -> {
            mutex.acquire(0);
            for (int j = 0; j < 10000; j++) {
                i++;
            }
            mutex.release(0);
        });

        Thread t2 = new Thread(() -> {
            mutex.acquire(0);
            for (int j = 0; j < 10000; j++) {
                i++;
            }
            mutex.release(0);
        });

        t1.start();
        t2.start();


        t1.join();
        t2.join();

        System.err.format("i = %d\n", i);
    }

}
